package com.du.springmvc.converter;

import com.du.springmvc.bean.Employee;
import com.du.springmvc.bean.Gender;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;

/**
 * @author : DuJiabao
 * @Project : spring-mvc
 * @Time : 2021/4/6 14:07
 * @Desc :
 */
@Component
public class StringToEmployeeConverterFactory implements ConverterFactory<String, Employee> {

  @Override
  public <T extends Employee> Converter<String, T> getConverter(Class<T> targetType) {
    return new StringToEmployee<>(targetType);
  }

  private static class StringToEmployee<T extends Employee> implements Converter<String, T> {
    private final Class<T> targetType;

    public StringToEmployee(Class<T> targetType) {
      this.targetType = targetType;
    }

    /**
     * 输入格式：id-name-genderCode
     *
     * @param source
     * @return
     */
    @Override
    public T convert(String source) {
      T t = null;
      String[] sources = source.split("-");
      int id = Integer.parseInt(sources[0]);
      String name = sources[1];
      Gender gender = "0".equals(sources[2]) ? Gender.female : Gender.male;
      try {
        t = targetType.getDeclaredConstructor().newInstance();
        Class<? super T> superclass = targetType.getSuperclass();

        Method setId = superclass.getDeclaredMethod("setId", Integer.class);
        setId.setAccessible(true);
        setId.invoke(t, id);

        Method setName = superclass.getDeclaredMethod("setName", String.class);
        setName.setAccessible(true);
        setName.invoke(t, name);

        Method setGender = superclass.getDeclaredMethod("setGender", Gender.class);
        setGender.setAccessible(true);
        setGender.invoke(t, gender);

        System.out.println(t);
      } catch (Exception e) {
        e.printStackTrace();
      }
      return t;
    }
  }
}
